const express = require("express")
const path = require("path")
const config = require("./config/config")
const app = express()
const routerUser = require("./routes/user");
const routerAdmin = require("./routes/admin");
const routerWx = require("./routes/wx");
const fs = require("fs")
const cors = require('cors');

// 链接数据库
require("./db/connect")


// 配置跨域选项
const corsOptions = {
    origin: '*',
    methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Content-Length', 'Authorization', 'Origin', 'Accept', 'X-Requested-With', 'token'],
    credentials: true
};

app.use(cors(corsOptions));

app.all('*', function (req, res, next) {
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});


const bodyParser = require("body-parser");

// 解析以 application/json 和 application/x-www-form-urlencoded 提交的数据
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())
//配置路由
// 注册用户路由
routerUser(app)
// 注册后台权限路由
routerAdmin(app)
routerWx(app)
//注册静态文件
app.use('/public', express.static(path.join(__dirname, 'public')));
//注册404
app.use(function (req, res, next) {
    var err = new Error('Not Found'); err.status = 404; next(err);
});


app.listen(config.host.port, (res) => {
    console.log("监听地址" + config.host.url + ":" + config.host.port)
})